package com.aeoj.clientmanagement.controller;


import com.aeoj.clientmanagement.constant.SystemConstant;
import com.aeoj.clientmanagement.domain.response.R;
import com.aeoj.clientmanagement.domain.user.SysUser;
import com.aeoj.clientmanagement.domain.user.dto.LoginUserDTO;
import com.aeoj.clientmanagement.domain.user.vo.SysUserVO;
import com.aeoj.clientmanagement.service.SysUserService;
import com.aeoj.clientmanagement.utils.user.UserUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

/**
 * UserController
 * author: ZSM
 * time: 2025-04-14 23:28
 */
@RestController
@RequestMapping("/client/user")
public class UserController {
    @Resource
    private SysUserService userService;

    @PostMapping("login")
    public R login(@RequestBody LoginUserDTO loginUserDTO, HttpServletRequest request) {
        SysUser loginUser = userService.login(loginUserDTO);
        if (loginUser == null) return R.error("用户名或密码错误");
        SysUserVO sysUserVO = SysUserVO.toSysUserVO(loginUser);
        request.getSession().setAttribute(SystemConstant.SESSION_REDIS_KEY, sysUserVO);
        return R.ok(sysUserVO);
    }

    @PostMapping("logout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute(SystemConstant.SESSION_REDIS_KEY);
        return R.ok("注销成功");
    }

    @PostMapping("register")
    public R register(@RequestBody LoginUserDTO loginUserDTO) {
        SysUser sysUser = userService.register(loginUserDTO);
        if (sysUser == null) return R.error("注册失败");
        return R.ok(SysUserVO.toSysUserVO(sysUser));
    }

    @GetMapping("get_current_user")
    public R getCurrentUser(HttpServletRequest request) {
        return R.ok(UserUtils.getLoginUser(request));
    }
}
